﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Text;

namespace LastoRevival.Website
{
	public class Theme
	{
		private const string CssHtml = "<link rel=\"stylesheet\" type=\"text/css\" href=\"{0}\" />";
		private const string Path = "~/Themes/{0}";

		public string Name { get; private set; }
		public string CssPaths { get; private set; }
		public string MobileCssPaths { get; private set; }

		private Theme()
		{

		}

		public static Theme Load(string name)
		{
			var virtualPath = string.Format(Path, name);

			var physicalDirectory = new DirectoryInfo(HttpContext.Current.Server.MapPath(virtualPath));

			// sanity check
			if (!physicalDirectory.Exists)
			{
				throw new DirectoryNotFoundException(string.Format("Unable to load theme '{0}'", name));
			}
			
			var cssPaths = new StringBuilder();

			foreach (var stylesheet in physicalDirectory.GetFiles("*.css"))
			{
				var cssPath = string.Format(@"{0}\{1}", virtualPath, stylesheet.Name);//stylesheet..Substring(stylesheet.LastIndexOf("\\"));

				cssPaths.AppendLine(string.Format(CssHtml, VirtualPathUtility.ToAbsolute(cssPath)));
			}

			var mobilePaths = new StringBuilder();
			
			var mobileDirectory = new DirectoryInfo(physicalDirectory.FullName + "\\mobilecss");

			if (mobileDirectory.Exists)
			{
				foreach (var stylesheet in mobileDirectory.GetFiles("*.css"))
				{
					var cssPath = string.Format(@"{0}\mobilecss\{1}", virtualPath, stylesheet.Name);
					mobilePaths.AppendLine(string.Format(CssHtml, VirtualPathUtility.ToAbsolute(cssPath)));
				}
			}

			return new Theme
			{
				CssPaths = cssPaths.ToString(),
				MobileCssPaths = mobilePaths.ToString(),
				Name = name,
			};

		}
	}
}